#coding=utf-8
import sys
import os
from   os.path import abspath, dirname

import devices_serial

sys.path.append(abspath(dirname(__file__)))
import tkinter
import tkinter.filedialog
from   tkinter import *
import Fun
ElementBGArray={}  
ElementBGArray_Resize={} 
ElementBGArray_IM={} 

import DbBase
import GridBase

def Form_1_onLoad(uiName):
    port_list = devices_serial.searchSerial()
    device_serial_port = Fun.GetElement(uiName, 'device_serial_port')
    device_serial_port_com = []
    for i in range(0, len(port_list)):
        device_serial_port_com.append(port_list[i].device)
    device_serial_port["values"] = device_serial_port_com
    if device_serial_port.get() == "0":  # 如果当前UI中的端口列表为空，则指定显示第一个
        device_serial_port.current(0)

def Button_12_onCommand(uiName,widgetName):
    txt = Fun.GetText(uiName, 'Button_12')
    device_type_text = Fun.GetElement(uiName, 'device_type').get().replace('\n','')
    device_serial_bps_text = Fun.GetElement(uiName, 'device_serial_bps').get().replace('\n','')
    device_name_text =  Fun.GetText(uiName, 'device_name').replace('\n','')
    device_serial_port_text = Fun.GetElement(uiName, 'device_serial_port').get().replace('\n','')
    device_remark_text = Fun.GetText(uiName, 'device_remark').replace('\n','')
    if txt == '修  改':
        res = DbBase.getData()
        ydata=GridBase.getSelected('devices_python', 'devices_list')
        for item in res:
            if device_serial_port_text == ydata[3] and item[0]!=ydata[0]:
                Fun.MessageBox("不能有多个相同的串口号存在")
                return
        if device_serial_port_text != ydata[3]:
            #操作原来的串口关闭
            devices_serial.closeListSerial(ydata[3])

        itemx = GridBase.editSelected('devices_python', 'devices_list', device_type_text, device_name_text, device_serial_port_text,device_serial_bps_text, device_remark_text)
        DbBase.editAccountInfo(itemx[0], device_type_text, device_name_text, device_serial_port_text,device_serial_bps_text, device_remark_text)
    else:
        res = DbBase.getData()
        for item in res:
            if device_serial_port_text == item[3]:
                Fun.MessageBox("不能添加多个相同的串口号")
                return
        devices_serial.openListSerial(device_serial_port_text,device_serial_bps_text)
        id = DbBase.addAccountInfo(device_type_text, device_name_text, device_serial_port_text,device_serial_bps_text, device_remark_text)
        GridBase.addItem('devices_python','devices_list',id,device_type_text, device_name_text, device_serial_port_text,device_serial_bps_text, device_remark_text)


    root = Fun.GetElement(uiName, 'root')
    root.destroy()
    treeview = Fun.GetElement('devices_python', 'devices_list')
    index = treeview.selection()
    if len(index) == 0:
        treeview.selection_set(treeview.get_children()[0])
